package com.gzs.learn.admin.service.impl;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.gzs.learn.admin.common.constant.AdminConstants;
import com.gzs.learn.admin.common.constant.GenConstants;
import com.gzs.learn.admin.common.core.text.CharsetKit;
import com.gzs.learn.admin.common.exception.CustomException;
import com.gzs.learn.admin.common.utils.SecurityUtils;
import com.gzs.learn.admin.common.utils.StringUtils;
import com.gzs.learn.admin.common.utils.file.FileUtils;
import com.gzs.learn.admin.mapper.GenTableColumnMapper;
import com.gzs.learn.admin.mapper.GenTableMapper;
import com.gzs.learn.admin.model.po.DbConfig;
import com.gzs.learn.admin.model.po.GenTable;
import com.gzs.learn.admin.model.po.GenTableColumn;
import com.gzs.learn.admin.model.vo.request.GenTableImportRequest;
import com.gzs.learn.admin.service.IDbConfigService;
import com.gzs.learn.admin.service.IGenTableService;
import com.gzs.learn.admin.util.GenUtils;
import com.gzs.learn.admin.util.PageUtil;
import com.gzs.learn.admin.util.VelocityInitializer;
import com.gzs.learn.admin.util.VelocityUtils;
import com.gzs.learn.common.util.JsonUtil;
import com.gzs.learn.inf.BaseResponseDto;
import com.gzs.learn.inf.PageResponseDto;
import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 业务 服务层实现
 *
 * @author guanzhisong
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class GenTableServiceImpl implements IGenTableService {

    private final GenTableMapper genTableMapper;

    private final GenTableColumnMapper genTableColumnMapper;

    private final IDbConfigService dbConfigService;

    /**
     * 查询业务信息
     *
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTable selectGenTableById(Long id) {
        GenTable genTable = genTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    /**
     * 查询业务列表
     *
     * @param genTable 业务信息
     * @return 业务集合
     */
    @Override
    public PageResponseDto<GenTable> selectGenTableList(GenTable genTable) {
        Page<?> page = PageUtil.getPage();
        IPage<GenTable> pageInfo = genTableMapper.selectGenTableList(page, genTable);
        return PageUtil.buildPageResponse(pageInfo);
    }

    /**
     * 查询据库列表
     *
     * @param genTable 业务信息
     * @return 数据库表集合
     */
    @Override
    public PageResponseDto<GenTable> selectDbTableList(GenTable genTable) {
        Page<?> page = PageUtil.getPage();
        Long dbId = genTable.getTableDbid();
        SqlSessionFactory sqlSessionFactory = SQLSESSION_HOLDER.get(dbId);
        if (sqlSessionFactory == null) {
            initSqlSessionFactory(dbId);
            sqlSessionFactory = SQLSESSION_HOLDER.get(dbId);
        }
        IPage<GenTable> pageInfo = null;
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            GenTableMapper mapper = sqlSession.getMapper(GenTableMapper.class);
            pageInfo = mapper.selectDbTableList(page, genTable);
        }
        return PageUtil.buildPageResponse(pageInfo);
    }

    /**
     * 查询据库列表
     *
     * @param request 表名称组
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableListByNames(GenTableImportRequest request) {
        SqlSessionFactory sqlSessionFactory = SQLSESSION_HOLDER.get(request.getDbId());
        if (sqlSessionFactory == null) {
            initSqlSessionFactory(request.getDbId());
            sqlSessionFactory = SQLSESSION_HOLDER.get(request.getDbId());
        }
        List<GenTable> genTables = Lists.newArrayList();
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            GenTableMapper genMappper = sqlSession.getMapper(GenTableMapper.class);
            genTables.addAll(genMappper.selectDbTableListByNames(request.getTables(), request.getSchema()));
        }
        return genTables;
    }

    /**
     * 修改业务
     *
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateGenTable(GenTable genTable) {
        String options = JsonUtil.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        int row = genTableMapper.updateGenTable(genTable);
        if (row <= 0) {
            return;
        }
        for (GenTableColumn cenTableColumn : genTable.getColumns()) {
            genTableColumnMapper.updateGenTableColumn(cenTableColumn);
        }
    }

    /**
     * 删除业务对象
     *
     * @param tableIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteGenTableByIds(Long[] tableIds) {
        genTableMapper.deleteGenTableByIds(tableIds);
        genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
    }

    /**
     * 导入表结构
     *
     * @param tableList 导入表列表
     */
    @Override
    @Transactional
    public void importGenTable(List<GenTable> tableList, GenTableImportRequest request) {
        String operator = SecurityUtils.getUsername();
        try {
            for (GenTable table : tableList) {
                String tableName = table.getTableName();
                GenUtils.initTable(table, operator);
                table.setTableDbid(request.getDbId());
                table.setTableSchema(request.getSchema());
                int row = genTableMapper.insertGenTable(table);
                if (row <= 0) {
                    continue;
                }
                // 保存列信息
                Long dbId = table.getTableDbid();
                SqlSessionFactory sqlSessionFactory = SQLSESSION_HOLDER.get(dbId);
                if (sqlSessionFactory == null) {
                    initSqlSessionFactory(dbId);
                    sqlSessionFactory = SQLSESSION_HOLDER.get(dbId);
                }
                List<GenTableColumn> genTableColumns = Lists.newArrayList();
                try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
                    GenTableColumnMapper mapper = sqlSession.getMapper(GenTableColumnMapper.class);
                    genTableColumns.addAll(mapper.selectDbTableColumnsByName(tableName, table.getTableSchema()));
                }
                for (GenTableColumn column : genTableColumns) {
                    GenUtils.initColumnField(column, table);
                    genTableColumnMapper.insertGenTableColumn(column);
                }
            }
        } catch (Exception e) {
            throw new CustomException("导入失败：" + e.getMessage());
        }
    }

    /**
     * 预览代码
     *
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(Long tableId) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableById(tableId);
        // 查询列信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);
        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, AdminConstants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

    /**
     * 生成代码（下载方式）
     *
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String tableName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 生成代码（自定义路径）
     *
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public void generatorCode(String tableName) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 查询列信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, AdminConstants.UTF8);
                tpl.merge(context, sw);
                try {
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                } catch (IOException e) {
                    throw new CustomException("渲染模板失败，表名：" + table.getTableName());
                }
            }
        }
    }

    /**
     * 批量生成代码（下载方式）
     *
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 查询列信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, AdminConstants.UTF8);
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, AdminConstants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            } catch (IOException e) {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }

    /**
     * 修改保存参数校验
     *
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(GenTable genTable) {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
            String options = JsonUtil.toJSONString(genTable.getParams());
            Map<String, Object> paramsObj = JsonUtil.parseObject(options, new TypeReference<Map<String, Object>>() {
            });
            if (paramsObj.get(GenConstants.TREE_CODE) == null
                    || StringUtils.isEmpty(paramsObj.get(GenConstants.TREE_CODE).toString())) {
                throw new CustomException("树编码字段不能为空");
            } else if (paramsObj.get(GenConstants.TREE_PARENT_CODE) == null
                    || StringUtils.isEmpty(paramsObj.get(GenConstants.TREE_PARENT_CODE).toString())) {
                throw new CustomException("树父编码字段不能为空");
            } else if (paramsObj.get(GenConstants.TREE_NAME) == null
                    || StringUtils.isEmpty(paramsObj.get(GenConstants.TREE_NAME).toString())) {
                throw new CustomException("树名称字段不能为空");
            }
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table   业务表信息
     * @param columns 业务字段列表
     */
    public void setPkColumn(GenTable table, List<GenTableColumn> columns) {
        for (GenTableColumn column : columns) {
            if (column.isPk()) {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn())) {
            table.setPkColumn(columns.get(0));
        }
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTable genTable) {
        if (StringUtils.isBlank(genTable.getOptions())) {
            return;
        }
        Map<String, Object> options =
                JsonUtil.parseObject(genTable.getOptions(), new TypeReference<Map<String, Object>>() {
                });
        if (options != null && options.size() > 0) {
            String treeCode = String.valueOf(options.get(GenConstants.TREE_CODE));
            String treeParentCode = String.valueOf(options.get(GenConstants.TREE_PARENT_CODE));
            String treeName = String.valueOf(options.get(GenConstants.TREE_NAME));
            String parentMenuId = String.valueOf(options.get(GenConstants.PARENT_MENU_ID));
            String parentMenuName = String.valueOf(options.get(GenConstants.PARENT_MENU_NAME));

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }

    /**
     * 获取代码生成地址
     *
     * @param table    业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, String template) {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/")) {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator
                    + VelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table);
    }

    @Override
    public BaseResponseDto<List<String>> selectSchemas(Long dbConfigId) {
        SqlSessionFactory sqlSessionFactory = SQLSESSION_HOLDER.get(dbConfigId);
        if (sqlSessionFactory == null) {
            initSqlSessionFactory(dbConfigId);
            sqlSessionFactory = SQLSESSION_HOLDER.get(dbConfigId);
        }
        List<String> schemas = Lists.newArrayList();
        try {
            try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
                GenTableMapper mapper = sqlSession.getMapper(GenTableMapper.class);
                schemas.addAll(mapper.selectSchemas());
            }
        } catch (Exception e) {
            log.error("execute schemas error", e);
            DS_HOLDER.remove(dbConfigId);
            SQLSESSION_HOLDER.remove(dbConfigId);
        }
        return BaseResponseDto.success(schemas);
    }


    /**
     * 初始化sqlSessionFactory
     *
     * @param dbConfigId
     * @return
     */
    private void initSqlSessionFactory(Long dbConfigId) {
        DbConfig config = dbConfigService.selectDbConfigById(dbConfigId);
        if (config == null) {
            throw new IllegalArgumentException("未找到指定的数据源配置:" + dbConfigId);
        }
        synchronized (this) {
            // 确保一次只有一个线程初始化
            if (SQLSESSION_HOLDER.get(dbConfigId) != null) {
                return;
            }
            HikariDataSource dataSource = new HikariDataSource();

            dataSource.setJdbcUrl(config.getUrl());
            dataSource.setUsername(config.getDbuser());
            dataSource.setPassword(config.getPwd());
            dataSource.setMinimumIdle(1);
            dataSource.setMaximumPoolSize(5);
            dataSource.setConnectionTestQuery("select 1 from dual");

            DS_HOLDER.put(dbConfigId, dataSource);
            String typeAliasPackage = String.format("%s.model,%s.common.**.domain", AdminConstants.SYSTEM_PREFIX);

            MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
            sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);
            sqlSessionFactoryBean.setDataSource(dataSource);
            sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis-gen.xml"));
            Interceptor[] plugins = {genMybatisPlusInterceptor()};
            sqlSessionFactoryBean.setPlugins(plugins);
            SqlSessionFactory sqlSessionFactory = null;
            try {
                sqlSessionFactory = sqlSessionFactoryBean.getObject();
            } catch (Exception e) {
                // 转换为运行时异常
                throw new IllegalArgumentException(e.getMessage());
            }

            SQLSESSION_HOLDER.put(dbConfigId, sqlSessionFactory);
        }
    }

    public MybatisPlusInterceptor genMybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 分页插件
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInnerInterceptor.setMaxLimit(AdminConstants.MAX_RECORDS_LIMIT);
        paginationInnerInterceptor.setOptimizeJoin(true);

        // 全表更新插件
        BlockAttackInnerInterceptor blockAttackInnerInterceptor = new BlockAttackInnerInterceptor();

        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        mybatisPlusInterceptor.addInnerInterceptor(blockAttackInnerInterceptor);
        return mybatisPlusInterceptor;
    }
}
